<?php
/**
 * 模型基本trait
 * Trait ModelQueryTrait
 */

namespace app\traits;

trait ModelQueryTrait
{

    public static function getOneByWhere(array $where = [], string $fields = 'id', string $order = 'id asc')
    {
        $data = self::where($where)->field($fields)->order($order)->find();
        return $data ? $data->toArray() : [];
    }

    public static function getOneById($id, $fields = '*')
    {
        $data = self::where(['id' => $id])->field($fields)->find();
        return $data ? $data->toArray() : [];
    }

    public static function getManyByIds(array $ids, string $fields = '*', string $order = 'id desc')
    {
        $data = self::where(['id' => $ids])->field($fields)->order($order)->select();
        return $data ? $data->toArray() : [];
    }

    public static function getByWhereAndLimit(array $where, string $fields = '*', string $order = 'id desc', int $limit = 0)
    {
        $model = self::where($where)->field($fields)->order($order);

        if ($limit) {
            $model->limit($limit);
        }

        $data = $limit == 1 ? $model->find() : $model->select();
        return $data ? $data->toArray() : [];
    }

}